/**
 * Copyright (C) 2010-2016 eBusiness Information, Excilys Group
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed To in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package org.ohosannotations.internal.core.handler;

import com.helger.jcodemodel.AbstractJClass;
import com.helger.jcodemodel.IJExpression;
import com.helger.jcodemodel.JBlock;
import com.helger.jcodemodel.JDefinedClass;
import com.helger.jcodemodel.JExpr;
import com.helger.jcodemodel.JInvocation;
import com.helger.jcodemodel.JMethod;
import com.helger.jcodemodel.JMod;
import com.helger.jcodemodel.JVar;

import org.ohosannotations.ElementValidation;
import org.ohosannotations.OhosAnnotationsEnvironment;
import org.ohosannotations.annotations.ItemSelect;
import org.ohosannotations.holder.EComponentWithViewSupportHolder;

import java.util.List;

import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;

import static com.helger.jcodemodel.JExpr._null;
import static com.helger.jcodemodel.JExpr.invoke;
import static com.helger.jcodemodel.JExpr.lit;

/**
 * 项目选择处理程序
 *
 * @author dev
 * @since 2021-07-22
 */
public class ItemSelectHandler extends AbstractViewListenerHandler {
    /**
     * ItemSelectHandler
     *
     * @param environment environment
     */
    public ItemSelectHandler(OhosAnnotationsEnvironment environment) {
        super(ItemSelect.class, environment);
    }

    /**
     * validate
     *
     * @param element element
     * @param validation validation
     */
    @Override
    public void validate(Element element, ElementValidation validation) {
        super.validate(element, validation);

        ExecutableElement executableElement = (ExecutableElement) element;

        validatorHelper.returnTypeIsVoid(executableElement, validation);

        validatorHelper.param.inOrder() //
            .primitiveOrWrapper(TypeKind.BOOLEAN) //
            .anyType().optional() //
            .validate(executableElement, validation);
    }

    /**
     * makeCall
     *
     * @param listenerMethodBody listenerMethodBody
     * @param call call
     * @param returnType returnType
     */
    @Override
    protected void makeCall(JBlock listenerMethodBody, JInvocation call, TypeMirror returnType) {
        listenerMethodBody.add(call);
    }

    /**
     * processParameters
     *
     * @param holder holder
     * @param listenerMethod listenerMethod
     * @param itemSelectedCall itemSelectedCall
     * @param parameters parameters
     */
    @Override
    protected void processParameters(EComponentWithViewSupportHolder holder,
        JMethod listenerMethod, JInvocation itemSelectedCall, List<? extends VariableElement> parameters) {
        JVar onItemClickParentParam = listenerMethod.param(getClasses().LIST_CONTAINER, "parent");
        listenerMethod.param(getClasses().COMPONENT, "component");
        JVar onItemClickPositionParam = listenerMethod.param(getCodeModel().INT, "position");
        listenerMethod.param(getCodeModel().LONG, "id");

        itemSelectedCall.arg(JExpr.TRUE);
        boolean hasItemParameter = parameters.size() == 2;
        boolean secondParameterIsInt = false;
        String secondParameterQualifiedName = null;
        if (hasItemParameter) {
            VariableElement secondParameter = parameters.get(1);
            TypeMirror secondParameterType = secondParameter.asType();
            secondParameterQualifiedName = secondParameterType.toString();
            secondParameterIsInt = secondParameterType.getKind() == TypeKind.INT;
        }

        if (hasItemParameter) {
            if (secondParameterIsInt) {
                itemSelectedCall.arg(onItemClickPositionParam);
            } else {
                itemSelectedCall.arg(JExpr.cast(getJClass(secondParameterQualifiedName),
                    invoke(onItemClickParentParam, "getItemProvider")
                        .invoke("getItem").arg(onItemClickPositionParam)));
            }
        }

        IJExpression abilityRef = holder.getGeneratedClass().staticRef("this");
        JInvocation nothingSelectedCall = invoke(abilityRef, getMethodName());
        nothingSelectedCall.arg(JExpr.FALSE);
        if (hasItemParameter) {
            if (secondParameterIsInt) {
                nothingSelectedCall.arg(lit(-1));
            } else {
                nothingSelectedCall.arg(_null());
            }
        }
    }

    /**
     * createListenerMethod
     *
     * @param listenerAnonymousClass listenerAnonymousClass
     * @return listenerAnonymousClass
     */
    @Override
    protected JMethod createListenerMethod(JDefinedClass listenerAnonymousClass) {
        return listenerAnonymousClass.method(JMod.PUBLIC,
            getCodeModel().VOID, "onItemSelected");
    }

    /**
     * getSetterName
     *
     * @return setItemSelectedListener
     */
    @Override
    protected String getSetterName() {
        return "setItemSelectedListener";
    }

    /**
     * getListenerClass
     *
     * @param holder holder
     * @return getClasses
     */
    @Override
    protected AbstractJClass getListenerClass(EComponentWithViewSupportHolder holder) {
        return getClasses().ITEM_SELECTED_LISTENER;
    }

    /**
     * getListenerTargetClass
     *
     * @param holder holder
     * @return getClasses
     */
    @Override
    protected AbstractJClass getListenerTargetClass(EComponentWithViewSupportHolder holder) {
        return getClasses().LIST_CONTAINER;
    }
}
